
from typing import List, Optional
from urllib.parse import urlparse
from fastapi import HTTPException, Request
from fastapi.params import Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from socket import AF_INET, SOCK_DGRAM, socket

def get_local_ip():
    s = socket(AF_INET, SOCK_DGRAM)
    try:
        # 不需要实际发送数据，只需要创建一个 UDP 包
        s.connect(("8.8.8.8", 80))  # Google 的公共 DNS 服务器
        local_ip = s.getsockname()[0]
        print("Local IP Address by connection:", local_ip)          
    finally:
        s.close()

    return local_ip

# 定义一个函数，用于从URL中获取IP地址
def get_ip_from_url(url):
    # 如果URL为空，则返回None
    if url is None:
        return None
    # 使用urlparse函数解析URL
    o = urlparse(url)
    # 返回URL的主机名，即IP地址
    return o.hostname    


get_bearer_token = HTTPBearer(auto_error=False)
async def check_api_key(api_keys: Optional[List[str]],
    auth: Optional[HTTPAuthorizationCredentials] = Depends(get_bearer_token),
) -> str:
    """Check if client provide valid api key.

    Adopted from https://github.com/lm-sys/FastChat/blob/v0.2.35/fastchat/serve/openai_api_server.py#L108-L127
    """  # noqa
    return None
    if api_keys:
        if auth is None or (
                token := auth.credentials) not in api_keys:
            raise HTTPException(
                status_code=401,
                detail={
                    'error': {
                        'message': 'Please request with valid api key!',
                        'type': 'invalid_request_error',
                        'param': None,
                        'code': 'invalid_api_key',
                    }
                },
            )
        return token
    else:
        # api_keys not set; allow all
        return None
    
async def check_ip(request: Request, ips=[]):
    client_ip = request.client.host
    if client_ip == "127.0.0.1":
        return None
    if client_ip in ips:
        return None
    raise HTTPException(
        status_code=401,
        detail={
            'error': {
                'message': 'request with valid ip!',
                'type': 'invalid_request_error',
                'param': None,
                'code': 'invalid_ip',
            }
        },
    )

async def check_ip_or_api_key(request: Request, api_keys: Optional[List[str]], ips=[]):
    return None
    client_ip = request.client.host
    if client_ip == "127.0.0.1":
        return None
    if client_ip in ips:
        return None
    return await check_api_key(api_keys)

async def check_ip_and_api_key(request: Request, api_keys: Optional[List[str]], ips=[]):
    client_ip = request.client.host
    if client_ip == "127.0.0.1":
        return await check_api_key(api_keys)
    if len(ips) == 0:
        return await check_api_key(api_keys)
    if client_ip not in ips:
        raise HTTPException(
            status_code=401,
            detail={
                'error': {
                    'message': 'request with valid ip!',
                    'type': 'invalid_request_error',
                    'param': None,
                    'code': 'invalid_ip',
                }
            },
        )
    return await check_api_key(api_keys)